package com.mobilebsc.httpclient.callback;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.mobilebsc.datatype.WeakSignal;

public class WeakSignalHttpResponseHandler extends JsonHttpResponseHandler {

	private static final String TAG = "WeakSignalHttpResponseHandler";
	private IAsyncTaskCompleteListener<List<WeakSignal>> callback;
	protected List<WeakSignal> weakSignalsList;

	public WeakSignalHttpResponseHandler(
			IAsyncTaskCompleteListener<List<WeakSignal>> callback) {
		super();
		this.callback = callback;
		weakSignalsList = null;
	}

	@Override
	public void onStart() {
		Log.i(TAG, "onStart = loading data");
	}

	@Override
	public void onSuccess(JSONArray weakSignals) {

		Log.i(TAG, "onSuccess = JSON length " + weakSignals.length()
				+ ", JSON string " + weakSignals.toString());

		weakSignalsList = new ArrayList<WeakSignal>();
		JSONObject weakSignalJSON = new JSONObject();

		if (weakSignals.length() == 0) {
			weakSignalsList.add(new WeakSignal());
		} else {
			for (int i = 0; i < weakSignals.length(); i++) {
				try {
					weakSignalJSON = weakSignals.getJSONObject(i);
					WeakSignal weakSignal = new WeakSignal(weakSignalJSON);
					weakSignalsList.add(weakSignal);
				} catch (JSONException e) {
					Log.e(TAG, "onSuccess = " + e.toString());
				}
			}
		}
	}

	@Override
	public void onSuccess(JSONObject singleWeakSignal) {
		weakSignalsList = new ArrayList<WeakSignal>();

		if (singleWeakSignal == null) {
			weakSignalsList.add(new WeakSignal());
		} else {
			try {
				WeakSignal weakSignal = new WeakSignal(singleWeakSignal);
				weakSignalsList.add(weakSignal);
			} catch (JSONException e) {
				Log.e(TAG, "onSuccess = " + e.toString());
			}
		}
	}

	@Override
	public void onFinish() {
		Log.i(TAG, "onFinish = finished");
		callback.onTaskComplete(weakSignalsList);
	}

	@Override
	public void onFailure(Throwable e, String response) {
		Log.e(TAG, "onFailure = " + e.toString() + "\n\n" + response);
	}
}
